"""
Author: Anthony Salgado
Date: December 7, 2011
"""

import sys

def main():
  
  w = sys.argv[1] if len(sys.argv) > 1 else 'foobar'
  for perm in allperms(w):
    print perm  

def allperms(word):
  """
  Generates every permutation, valid or invalid,
  of the argument word using Python generators.
  """
  if not word or len(word) == 1:
    yield word
  else:
    visited = {}
    for i in range(len(word)):
      first = word[i]
      if not visited.get(first,0):
        visited[first] = 1
        rest = word[:i] + word[i+1:]
        for perm in allperms(rest):
          yield first + perm
    
if __name__ == '__main__':
  main()
      
